package server

import (
	"car_rental/shared/auth"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"net"
)

// Config 定义GRPC服务器
type Config struct {
	Name              string
	Addr              string
	AuthPublicKeyFile string
	RegisterFunc      func(server *grpc.Server)
	*zap.Logger
}

func RunGrpcServer(c *Config) error {

	nameField := zap.String("name", c.Name)

	listen, err := net.Listen("tcp", c.Addr)

	if err != nil {
		c.Logger.Fatal("监听端口失败", nameField, zap.Error(err))
	}

	var opts []grpc.ServerOption

	if c.AuthPublicKeyFile != "" {

		// 认证拦截
		in, err := auth.Interceptor(c.AuthPublicKeyFile)

		if err != nil {
			c.Logger.Fatal("无法创建认证拦截器", nameField, zap.Error(err))
		}

		opts = append(opts, grpc.UnaryInterceptor(in))

	}

	s := grpc.NewServer(opts...)

	c.RegisterFunc(s)

	c.Logger.Sugar().Info("服务启动", nameField, zap.String("addr", c.Addr))

	return s.Serve(listen)

}
